#include "timer.h"

int32_t pid_speed = 0;
int32_t encoder_value;

void TIM6_IRQ(void)
{   
  encoder_test();
}

void encoder_test(void)
{
  static int32_t enc_now, enc_err, enc_last, enc_err_last, value;

  enc_now = __HAL_TIM_GET_COUNTER(&htim1);

  enc_err = enc_now - enc_last;

  if (enc_err > 20000)
    enc_err = -enc_last - (0xffff - enc_now); 
  if (enc_err < -20000)
    enc_err = enc_now + (0xffff - enc_last); 

  value = enc_err;
		
  enc_err_last = enc_err;
  enc_last = enc_now;

  encoder_value = value/27;

  // printf("%d\r\n", encoder_value);

  static uint16_t i = 0, a = 0;
  if (i > 100)
  {
    a =! a;
    HAL_GPIO_WritePin(GPIOE, GPIO_PIN_5, a);
    i = 0;
  }
  else
  {
    i++;
  }

}

void EXTI0_IRQ(void)
{
  if (KEY0 == 1)  //WK_UP按键
  {
    pid_speed++;
  }
 
}

void EXTI4_IRQ(void)
{
  if (KEY1 == 1) //按键KEY0
  {
    pid_speed--;
  }

}